<template>
  <el-card class="goods-report-container">
    <template #header>
      <el-config-provider :locale="zhCn">
        <div class="header">
          <!-- 时间筛选 -->
          <el-date-picker
              v-model="state.dateRange"
              type="daterange"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              style="width: 300px; margin-right: 10px"
              @change="handleDateChange"
              value-format="YYYY-MM-DD"
              format="YYYY-MM-DD"
              :unlink-panels="true"
          />

          <!-- 开票状态筛选 -->
          <el-select
              v-model="state.billStatus"
              style="width: 150px; margin-right: 10px"
              placeholder="开票状态"
              @change="handleFilterChange"
          >
            <el-option label="全部" value=""></el-option>
            <el-option label="已开票" value="4"></el-option>
            <el-option label="未开票" value="1"></el-option>
            <el-option label="开票申请中" value="2"></el-option>
            <el-option label="商家同意开票" value="3"></el-option>
          </el-select>

          <!-- 退款状态筛选 -->
          <el-select
              v-model="state.refundStatus"
              style="width: 150px; margin-right: 10px"
              placeholder="退款状态"
              @change="handleFilterChange"
          >
            <el-option label="全部" value=""></el-option>
            <el-option label="已退款" value="已退款"></el-option>
            <el-option label="未退款" value="未退款"></el-option>
            <el-option label="用户申请退款" value="用户申请退款"></el-option>
            <el-option label="业务员退款通过" value="业务员退款通过"></el-option>
          </el-select>

          <el-button type="primary" :icon="Search" @click="getGoodsReport">查询</el-button>
          <el-button type="success" :icon="Download" @click="handleExport">导出报表</el-button>
        </div>
      </el-config-provider>
      <!-- 汇总统计 -->
      <div class="summary-card">
        <el-card shadow="never" class="summary-content">
          <div class="summary-items">
            <div class="summary-item">
              <span class="label">总销售数量：</span>
              <span class="value">{{ state.summary.totalSales }}</span>
            </div>
            <div class="summary-item">
              <span class="label">总销售金额：</span>
              <span class="value" style="color: #f56c6c">¥{{ state.summary.totalAmount.toFixed(2) }}</span>
            </div>
            <div class="summary-item">
              <span class="label">总退款金额：</span>
              <span class="value" style="color: #f56c6c">-¥{{ state.summary.totalRefundAmount.toFixed(2) }}</span>
            </div>
            <div class="summary-item">
              <span class="label">净销售额：</span>
              <span class="value" style="color: #67c23a">¥{{ state.summary.netAmount.toFixed(2) }}</span>
            </div>
            <div class="summary-item">
              <span class="label">已开票数量：</span>
              <span class="value">{{ state.summary.totalBilledCount }}</span>
            </div>
            <div class="summary-item">
              <span class="label">未开票数量：</span>
              <span class="value">{{ state.summary.totalUnbilledCount }}</span>
            </div>
          </div>
        </el-card>
      </div>
    </template>

    <!-- 商品汇总表格 -->
    <el-table
        :data="state.goodsData"
        v-loading="state.loading"
        style="width: 100%"
        @row-click="handleRowClick"
        :row-class-name="tableRowClassName"
    >
      <el-table-column prop="goodsId" label="商品ID" width="80" />
      <el-table-column prop="goodsName" label="商品名称" min-width="200" show-overflow-tooltip />
      <el-table-column prop="goodsCoverImg" label="商品图片" width="100">
        <template #default="scope">
          <el-image
              style="width: 50px; height: 50px"
              :src="scope.row.goodsCoverImg"
              :preview-src-list="[scope.row.goodsCoverImg]"
              fit="cover"
          />
        </template>
      </el-table-column>
      <el-table-column prop="totalSales" label="销售数量" width="100" sortable />
      <el-table-column prop="totalAmount" label="销售金额" width="120" sortable>
        <template #default="scope">
          <span style="color: #f56c6c; font-weight: bold">
            ¥{{ scope.row.totalAmount.toFixed(2) }}
          </span>
        </template>
      </el-table-column>
      <el-table-column prop="refundCount" label="退款数量" width="100" sortable>
        <template #default="scope">
          <span v-if="scope.row.refundCount > 0" style="color: #f56c6c">
            {{ scope.row.refundCount }}
          </span>
          <span v-else>{{ scope.row.refundCount }}</span>
        </template>
      </el-table-column>
      <el-table-column prop="refundAmount" label="退款金额" width="120" sortable>
        <template #default="scope">
          <span v-if="scope.row.refundAmount > 0" style="color: #f56c6c">
            -¥{{ scope.row.refundAmount.toFixed(2) }}
          </span>
          <span v-else>¥0.00</span>
        </template>
      </el-table-column>
      <el-table-column prop="netAmount" label="净销售额" width="120" sortable>
        <template #default="scope">
          <span style="color: #67c23a; font-weight: bold">
            ¥{{ scope.row.netAmount.toFixed(2) }}
          </span>
        </template>
      </el-table-column>
      <el-table-column prop="billedCount" label="已开票数量" width="120" sortable>
        <template #default="scope">
          <el-tag v-if="scope.row.billedCount > 0" type="success" size="small">
            {{ scope.row.billedCount }}
          </el-tag>
          <span v-else>{{ scope.row.billedCount }}</span>
        </template>
      </el-table-column>
      <el-table-column prop="unbilledCount" label="未开票数量" width="120" sortable>
        <template #default="scope">
          <el-tag v-if="scope.row.unbilledCount > 0" type="info" size="small">
            {{ scope.row.unbilledCount }}
          </el-tag>
          <span v-else>{{ scope.row.unbilledCount }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="120" fixed="right">
        <template #default="scope">
          <el-button type="primary" link @click.stop="handleRowClick(scope.row)">
            订单明细
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页组件 -->
    <el-pagination
        background
        layout="prev, pager, next, sizes, total"
        :total="state.total"
        :page-size="state.pageSize"
        :current-page="state.currentPage"
        :page-sizes="[10, 20, 50, 100]"
        @size-change="handleSizeChange"
        @current-change="handlePageChange"
        style="margin-top: 20px; justify-content: flex-end;"
    />



    <!-- 订单明细弹窗 -->
    <!-- 订单明细弹窗 - 添加可移动功能 -->
    <el-dialog
        v-model="state.orderDetailVisible"
        :title="`商品订单明细 - ${state.selectedGoods?.goodsName || ''}`"
        width="90%"
        top="5vh"
        draggable
        modal-class="movable-dialog"
    >
      <order-detail-table
          :goods-id="state.selectedGoods?.goodsId"
          :goods-name="state.selectedGoods?.goodsName"
          :date-range="state.dateRange"
          :bill-status="state.billStatus"
          :refund-status="state.refundStatus"
          v-if="state.orderDetailVisible"
      />
    </el-dialog>
  </el-card>
</template>

<script setup>
import { reactive, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import { Search, Download } from '@element-plus/icons-vue'
import zhCn from 'element-plus/es/locale/lang/zh-cn'
import axios from '@/utils/axios'
import OrderDetailTable from './OrderDetailTable.vue'

const state = reactive({
  loading: false,
  goodsData: [],
  total: 0,
  currentPage: 1,
  pageSize: 10,
  dateRange: [],
  billStatus: '',
  refundStatus: '',
  orderDetailVisible: false,
  selectedGoods: null,
  summary: {
    totalSales: 0,
    totalAmount: 0,
    totalRefundAmount: 0,
    netAmount: 0,
    totalBilledCount: 0,
    totalUnbilledCount: 0
  }
})

// 表格行点击样式
const tableRowClassName = ({ row }) => {
  return 'clickable-row'
}

// 日期变化处理
const handleDateChange = (val) => {
  if (val && val.length === 2) {
    state.currentPage = 1 // 重置到第一页
    getGoodsReport()
  }
}

// 筛选条件变化
const handleFilterChange = () => {
  state.currentPage = 1 // 重置到第一页
  getGoodsReport()
}

// 获取商品汇总数据
const getGoodsReport = async () => {
  state.loading = true
  try {
    const params = {
      pageNumber: state.currentPage,
      pageSize: state.pageSize,
      startTime: state.dateRange?.[0] || '',
      endTime: state.dateRange?.[1] || '',
      billStatus: state.billStatus,
      refundStatus: state.refundStatus
    }

    console.log("请求参数:", params)

    const response = await axios.get('/goodsReport', { params })


    console.log("响应数据:", response)

    state.goodsData = response.list || []
    state.total = response.totalCount || 0
    state.currentPage = response.currPage || 1
    state.pageSize = response.pageSize || 10

    // 更新汇总数据
    if (response.summary) {
      state.summary = response.summary
    }

    ElMessage.success('数据加载成功')
  } catch (error) {
    console.error('获取商品汇总数据失败:', error)
    ElMessage.error('数据加载失败: ' + (error.response?.data?.message || error.message))
  } finally {
    state.loading = false
  }
}

// 分页大小变化
const handleSizeChange = (val) => {
  state.pageSize = val
  state.currentPage = 1
  getGoodsReport()
}

// 页码变化
const handlePageChange = (val) => {
  state.currentPage = val
  getGoodsReport()
}

// 点击行查看订单明细
const handleRowClick = (row) => {
  state.selectedGoods = row
  state.orderDetailVisible = true
}

// 导出报表
const handleExport = async () => {
  try {
    const params = {
      startTime: state.dateRange?.[0] || '',
      endTime: state.dateRange?.[1] || '',
      billStatus: state.billStatus,
      refundStatus: state.refundStatus
    }

    const queryString = Object.keys(params)
        .filter(key => params[key] !== undefined && params[key] !== null && params[key] !== '')
        .map(key => `${encodeURIComponent(key)}=${encodeURIComponent(params[key])}`)
        .join('&')

    const url = `http://172.26.200.76:28019/manage-api/v1/exportGoodsReport?${queryString}`
    console.log('导出URL:', url)
    window.open(url, '_blank')

    ElMessage.success('导出请求已发送')
  } catch (error) {
    console.error('导出失败:', error)
    ElMessage.error('导出失败: ' + error.message)
  }
}

onMounted(() => {
  // 默认查询最近30天的数据
  const endDate = new Date()
  const startDate = new Date()
  startDate.setDate(startDate.getDate() - 30)

  state.dateRange = [
    startDate.toISOString().split('T')[0],
    endDate.toISOString().split('T')[0]
  ]

  getGoodsReport()
})
</script>

<style scoped>
.goods-report-container {
  min-height: 800px;
}

.header {
  display: flex;
  align-items: center;
  flex-wrap: wrap;
  gap: 10px;
}

.summary-card {
  margin-top: 20px;
  border: 1px solid #e6e6e6;
  border-radius: 4px;
}

.summary-content {
  background-color: #f8f9fa;
}

.summary-items {
  display: flex;
  flex-wrap: wrap;
  gap: 30px;
  padding: 10px 0;
}

.summary-item {
  display: flex;
  align-items: center;
}

.summary-item .label {
  font-weight: 500;
  color: #606266;
}

.summary-item .value {
  font-weight: bold;
  font-size: 16px;
}

:deep(.clickable-row) {
  cursor: pointer;
}

:deep(.clickable-row:hover > td) {
  background-color: #f5f7fa !important;
}


/* 可移动对话框样式 */
:deep(.movable-dialog) {
  position: fixed;
}

:deep(.movable-dialog .el-dialog__header) {
  cursor: move;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  padding: 15px 20px;
}

:deep(.movable-dialog .el-dialog__title) {
  color: white;
  font-weight: 600;
}

:deep(.movable-dialog .el-dialog__headerbtn) {
  top: 15px;
}

:deep(.movable-dialog .el-dialog__headerbtn .el-dialog__close) {
  color: white;
}

:deep(.movable-dialog .el-dialog__headerbtn:hover .el-dialog__close) {
  color: #f56c6c;
}


</style>
